<template>
    <view class="content-box">
        <view class="option">
            <template v-for="(item, key) in withdrawTypesMap">
                <view @tap="changeWithdrawalsType(item, key)" v-if="withdrawTypes.indexOf(key) > -1" :key="key" :class="[currentWithdrawType === key ? 'active' : '', $i18n.locale]">
                    {{ item.label }}
                </view>
            </template>
        </view>
        <view class="from">
            <view class="font-30 flex-tip">
                <view style="width: 240rpx">{{ $t('withdrawPage.entryAccount') }}</view>
                <view @tap="choose_card">
                    <view class="wechat" :class="[$i18n.locale]" v-if="selectedBankCard.bank_card">{{ selectedBankCard.bankname }}({{ selectedBankCard.bank_card }})</view>
                    <view class="wechat" :class="[$i18n.locale]" v-else-if="currentWithdrawType === '2'">{{ $t('withdrawPage.withdrawTypes[1]') }}({{ user.nickname }})</view>
                    <view v-else class="wechat" :class="[$i18n.locale]">{{ $t('withdrawPage.pleaseSelect') }}</view>
                    <view class="c7">{{ $t('withdrawPage.bookingFee') }}{{ charge.toFixed(2) }}%</view>
                </view>
            </view>
            <view class="font-30" style="margin-top: 50rpx">{{ $t('withdrawPage.amount') }}</view>
            <view class="account-input-box">
                <view class="font-48" style="margin-right: 20rpx;">{{ $t('unit') }}</view>
                <input class="account-input inline" style="font-size: 40rpx;" @blur="checkWithdrawMoney" v-model="withdrawMoney" type="number" :placeholder="$t('withdrawPage.amountPlaceholder')" />
            </view>

            <view class="font-26 flex">
                <view>{{ $t('withdrawPage.withdrawMoneyLimit') }} {{ $t('withdrawPage.availableBalance') }}{{ user_money }}</view>
                <view class="all-with" :class="[$i18n.locale]" @tap="all_number">{{ $t('withdrawPage.fullEntry') }}</view>
            </view>

            <view class="font-30" style="margin-top: 50rpx">{{ $t('withdrawPage.commissionEntry') }}</view>
            <view class="uni-list">
                <radio-group @change="changeCommissionType">
                    <label v-for="(item, index) in commissionTypes" :key="item.value">
                        <view class="uni-list-cell uni-list-cell-pd">
                            <view>
                                <radio :color="$i18n.locale === 'zh' ? '#77c25a': '#00be5f'" :value="item.value" :checked="item.value === currentCommissionType" />
                            </view>
                            <view>{{ item.name }}</view>
                        </view>
                        <view class="uni-list-cell-tips" v-if="item.value === currentCommissionType">
                            <block v-if="item.value === '1'">
                                <view class="">
                                    <text style="margin-right: 10rpx;">
                                        {{ $t('withdrawPage.convergenceInternational') }} {{ $t('withdrawPage.currentPrice') }}{{ stockPrice }}
                                    </text>
                                    <text v-if="$i18n.locale === 'zh'">{{ $t('withdrawPage.exchangeRate') }}{{ exchangeRate }}</text>
                                </view>
                                <view v-if="withdrawMoney">
                                    {{ $t('withdrawPage.thisEntry') }}{{ withdrawMoney }}， {{ $t('withdrawPage.obtain') }}{{ stock }}{{ $t('withdrawPage.stocks') }}
                                </view>
                                <view>{{ $t('withdrawPage.withdrawMoneyLimit') }}</view>
                            </block>
                            <!-- <block v-else-if="index === 1">
                                <view class="">荟萃国际 现价：{{ stockPrice }} 汇率：{{ exchangeRate }}</view>
                                <view class="">
                                    <text>本次入账{{ money }}元， 获得{{ count }}股</text>
                                    <text v-if="users_type === 1 && user.is_tax === 1">，扣稅{{ taxFee }}元</text>
                                </view>
                                <view>入账只限100的倍数</view>
                            </block> -->
                            <block v-else-if="item.value === '3'">
                                <view v-if="users_type === '1'">{{ $t('withdrawPage.deductThe5TaxRate') }}</view>
                                <!-- <view v-if="users_type === '1'">本次入账{{ money }}元， 扣稅{{ taxFee }}元</view> -->
                                <view>{{ $t('withdrawPage.withdrawMoneyLimit') }}</view>
                            </block>
                        </view>
                    </label>
                </radio-group>
            </view>

            <view class="font-30" style="margin-top: 50rpx">{{ $t('withdrawPage.wayOfEntry') }}</view>
            <view class="uni-list">
                <view class="uni-list-cell uni-list-cell-pd">
                    <radio-group @change="usersTypeChange">
                        <label>
                            <view class="uni-list-cell uni-list-cell-pd">
                                <view>
                                    <radio :color="$i18n.locale === 'zh' ? '#77c25a': '#00be5f'" name="users_type" value="1" :checked="users_type === '1'" />
                                </view>
                                <view>{{ $t('withdrawPage.individual') }}</view>
                            </view>
                        </label>
                        <label>
                            <view class="uni-list-cell uni-list-cell-pd">
                                <view>
                                    <radio :color="$i18n.locale === 'zh' ? '#77c25a': '#00be5f'" name="users_type" value="2" :checked="users_type === '2'" />
                                </view>
                                <view>{{ $t('withdrawPage.enterprise') }}</view>
                            </view>
                            <view v-if="users_type === '2' && currentCommissionType === '3'">
                                <view class="tax_path" @click="chooseTaxPath" v-if="!tax_path">
                                    <view class="">{{ $t('withdrawPage.taxVoucher') }}</view>
                                    <view class="upload-icon">+</view>
                                </view>
                                <view class="tax_path" v-else>
                                    <view class="" style="margin-right: 20rpx;">{{ $t('withdrawPage.taxVoucher') }}</view>
                                    <image :src="$image + tax_path" mode="" style="width: 100rpx; height: 100rpx;"></image>
                                </view>
                            </view>
                        </label>
                    </radio-group>
                </view>
            </view>

            <view class="buttom font-32" :class="[$i18n.locale]" @tap="subimt">{{ $t('confirm') }}</view>
        </view>
        <view class="rich-box"><rich-text :nodes="contxt"></rich-text></view>
        <pay-account v-model="card_dialog" @change="selectBankCard" @to_add="to_add" :go="false" :list="card_list"></pay-account>
        <!-- 支付密码 -->
        <!-- <pay-password ref="pay" v-model="pay_dialog" :show="false" @check_word="save"></pay-password> -->
        <pay-password ref="payPassword" @onChange="payPwdTap"></pay-password>
        <!-- <no-password v-model="no_password" @check="set_password" /> -->
    </view>
</template>

<script>
    import {
        mapState
    } from 'vuex'
    import payAccount from '../components/pay_account.vue'
    // import payPassword from 'index/components/pay_password.vue'
    import payPassword from 'index/components/payPassword_new.vue'
    // import noPassword from 'index/components/no_password.vue'

    export default {
        data() {
            return {
                // 提现文案
                contxt: '',
                withdrawMoney: '',
                // 提现类型 1: 银行卡 2: 微信 3:支付宝 4:PayPal
                // 卡的类型 1: 银行卡 2: 支付宝 3: PayPal
                typesMap: {
                    1: '1',
                    3: '2',
                    4: '3'
                },
                withdrawTypesMap: {
                    1: {
                        label: this.$t('withdrawPage.withdrawTypes[0]')
                    },
                    2: {
                        label: this.$t('withdrawPage.withdrawTypes[1]')
                    },
                    3: {
                        label: this.$t('withdrawPage.withdrawTypes[2]')
                    },
                    4: {
                        label: this.$t('withdrawPage.withdrawTypes[3]')
                    }
                },
                withdrawTypes: [],
                currentWithdrawType: -1,
                selectedBankCard: {},
                commissionTypes: [{
                        name: this.$t('withdrawPage.commissionTypes[0]'),
                        value: '1'
                    },
                    // {
                    //     name: '50%现金+50%荟萃国际',
                    //     value: '2'
                    // },
                    {
                        name: this.$t('withdrawPage.commissionTypes[1]'),
                        value: '3'
                    }
                ],
                currentCommissionType: '1',
                card_list: [],
                card_dialog: false,
                user_money: '0.00',
                distribut_min: '',
                charge: 0,
                pay_dialog: false,
                // no_password: false,
                payPwd: '',
                stockPrice: '',
                exchangeRate: null,
                timer: null,
                users_type: '1',
                tax_path: '',
                taxFee: 0
            }
        },
        onUnload() {
            clearInterval(this.timer)
        },
        onLoad() {
            // this.getStockPrice()
            uni.setNavigationBarTitle({
                title: this.$t('withdrawPage.navigationBarTitle')
            })
        },
        async onShow() {
            this.init()
        },
        methods: {
            init() {
                this.getRule()
                this.getWithdrawals()
                if (this.users_type === '2') {
                    this.to_identification()
                }
            },
            getRule() {
                this.$http('post|api/Article/regulation', {
                    id: 9
                }).then(res => {
                    this.contxt = res.result.topic_content
                })
            },
            getWithdrawals() {
                this.withdrawals()
                    .then(_ => {
                        // this.option[0].name = `微信${this.user.nickname}`
                    })
                    .catch(res => {
                        if (res.status === -2) {
                            uni.showModal({
                                title: this.$t('showModalTitle'),
                                content: this.$t('withdrawPage.showModalContent'),
                                success: function(res) {
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '/my/mdf_password/mdf_password'
                                        })
                                    } else if (res.cancel) {
                                        uni.navigateBack()
                                    }
                                }
                            })
                        }
                    })
            },
            withdrawals() {
                uni.showLoading({
                    title: this.$t('loading')
                })
                return this.$http('get|api/User/withdrawals', {
                    bank_type: this.currentWithdrawType
                }).then(res => {
                    // withdraw_type  1是银行卡，2是微信，3是支付宝,4是PayPal
                    this.withdrawTypes = res.result.withdraw_type.map(x => x.toString())
                    if (this.currentWithdrawType === -1) {
                        Object.keys(this.withdrawTypesMap).find(key => {
                            const index = this.withdrawTypes.indexOf(key)
                            if (index > -1) {
                                this.currentWithdrawType = key
                                return true
                            }
                        })
                    }
                    // const list = res.result.bankcard_list || []
                    // this.card_list = list.filter(x => (x.active = true))
                    this.stockPrice = res.result.stockPrice
                    this.exchangeRate = res.result.exchangeRate
                    this.user_money = res.result.user_money
                    this.charge = +res.result.charge
                    this.distribut_min = +res.result.distribut_min
                })
            },
            choose_card() {
                if (this.currentWithdrawType !== '2') {
                    uni.showLoading({
                        title: this.$t('loading')
                    })

                    const bank_type = this.typesMap[this.currentWithdrawType]
                    this.$http('get|api/User/withdrawals', {
                        bank_type: bank_type
                    }).then(res => {
                        const list = res.result.bankcard_list || []
                        this.card_list = list.map(x => {
                            if (this.selectedBankCard.bank_id === x.bank_id) {
                                x.active = this.selectedBankCard.active
                            } else {
                                x.active = false
                            }
                            return x
                        })
                        this.card_dialog = true
                    })
                }
            },
            to_add() {
                const bank_type = this.typesMap[this.currentWithdrawType]
                uni.navigateTo({
                    url: `/my/pay_account/pay_account?bank_type=${bank_type}`,
                    events: {
                        acceptDataFromOpenedPage: data => {
                            this.choose_card()
                        }
                    }
                })
            },
            checkWithdrawMoney(e) {
                let value = e.detail.value
                if (value) {
                    value = parseInt(e.detail.value)
                    let remainder = value % 100
                    if (remainder !== 0 || value === 0) {
                        uni.showToast({
                            title: this.$('withdrawPage.withdrawMoneyLimit'),
                            icon: 'none'
                        })
                    }
                }
            },
            all_number() {
                this.withdrawMoney = this.user_money
            },
            changeCommissionType(e) {
                const value = e.detail.value
                this.currentCommissionType = value
            },
            count_tax(money) {
                return this.$http('get|api/user/count_tax', {
                    money
                })
            },
            chooseTaxPath() {
                let that = this
                uni.chooseImage({
                    count: 1,
                    sizeType: 'compressed',
                    success: chooseImageRes => {
                        uni.showLoading({
                            mask: true,
                            title: this.$t('loading')
                        })
                        this.$uploadCom(chooseImageRes).then(res => {
                            that.tax_path = res.result
                            uni.hideLoading()
                            that.$forceUpdate()
                            uni.showToast({
                                title: this.$t('uploadSuccess')
                            })
                        })
                    }
                })
            },
            usersTypeChange(e) {
                this.users_type = e.detail.value
                if (this.users_type === '2') {
                    // 企业认证
                    this.to_identification()
                }
            },
            to_identification() {
                uni.showLoading({
                    title: this.$t('loading')
                })
                this.$http('get|api/user/apply_partner').then(res => {
                    // console.log('get|api/user/apply_partner', res)
                    const user_embassy = res.result.user_embassy
                    if (user_embassy.status === -3) {
                        uni.showModal({
                            content: this.$t('withdrawPage.enterpriseShowModalContent'),
                            success: res => {
                                if (res.confirm) {
                                    uni.navigateTo({
                                        url: '/my/agent/agent'
                                    })
                                } else if (res.cancel) {
                                    this.users_type = '1'
                                }
                            }
                        })
                    } else if (user_embassy.status !== 1) {
                        this.$toastApp(user_embassy.msg)
                        this.users_type = '1'
                    } else if (res.status !== 1) {
                        this.$toastApp(res.msg)
                    }
                    uni.hideLoading()
                })
            },
            getStockPrice() {
                this.timer = setInterval(() => {
                    this.$http('get|api/User/withdrawals', {}).then(res => {
                        this.stockPrice = res.result.stockPrice
                        this.exchangeRate = res.result.exchangeRate
                        // console.log('getStockPrice', res)
                    })
                }, 8000)
            },
            selectBankCard(e) {
                this.selectedBankCard = e
                this.card_dialog = false
            },
            changeWithdrawalsType(item, key) {
                this.currentWithdrawType = key
                if (this.currentWithdrawType === '2') {
                    // 微信
                    this.selectedBankCard = {}
                } else {}
            },
            subimt() {
                if (!this.withdrawMoney) {
                    this.$toastApp(this.$t('withdrawPage.withdrawMoneyPlaceholder'))
                    return
                }
                if (this.withdrawMoney % this.distribut_min !== 0) {
                    this.$toastApp(this.$t('withdrawPage.withdrawMoneyLimit'))
                    return
                }
                // 过滤微信校验
                if (!this.selectedBankCard.bank_id && this.currentWithdrawType !== '2') {
                    this.$toastApp(this.$t('withdrawPage.bankPlaceholder'))
                    return
                }

                // 企业提现 100%现金 校验
                if (this.users_type === '2' && this.currentCommissionType === '3' && !this.tax_path) {
                    this.$toastApp(this.$t('withdrawPage.taxPathPlaceholder'))
                    return
                }

                const index = this.commissionTypes.findIndex(item => item.value === this.currentCommissionType)
                let title = this.$t('withdrawPage.commissionShowModalTitle') + this.commissionTypes[index].name
                let content = ''
                // is_tax: 1 || 2 是否缴税
                // users_type: 1 || 2 个人或企业
                content = this.$t('withdrawPage.individualShowModalContent')
                // if (this.users_type === '1' && this.currentCommissionType === '3') {
                //     content = this.$t('withdrawPage.individualShowModalContent')
                // } else {
                //     content = '如在14日冷静期内销售订单出现退单，将会向阁下收取其所产生的所有费用包括但不限于手续费、服务费、律师费。'
                // }
                uni.showModal({
                    title: title,
                    content: content,
                    success: res => {
                        if (res.confirm) {
                            this.$refs.payPassword.showPay()
                        }
                    }
                })
            },
            postWithdrawals(payPwd) {
                uni.showLoading({
                    mask: true
                })
                // bank_id: '', 卡的ID
                // money: '',提现金额
                // paypwd: '',支付密码
                // type: 3 , 提现方式: 1:银行卡 2:微信 3:支付宝 4:paypal
                // money_type 佣金提现方式 1: 100%荟萃国际 2:50%股票+50%现金 3:100%现金
                // users_type 提现方式 1: 个人 2: 企业
                // tax_path 企业提现 100%现金 条件 money_type === 3 && users_type === 2
                const data = {
                    paypwd: payPwd,
                    bank_id: this.selectedBankCard.bank_id,
                    money: this.withdrawMoney,
                    type: this.currentWithdrawType,
                    money_type: this.currentCommissionType,
                    users_type: this.users_type
                }
                if (this.tax_path) {
                    data.tax_path = this.tax_path
                }
                console.log('post|api/User/withdrawals', data)
                this.$http('post|api/User/withdrawals', data)
                    .then(res => {
                        this.$toastApp(res.msg)
                        uni.navigateBack()
                    })
                    .catch(e => {
                        console.log('error', e)
                        this.$toastApp(e.msg, 'none')
                        this.$refs.pay.passworld = []
                    })
            },
            // 支付密码输入
            payPwdTap(i) {
                this.payPwd = i.join('')
                if (this.payPwd.length === 6) {
                    this.postWithdrawals(this.payPwd)
                    return
                }
            }
        },
        watch: {
            card_dialog(val) {
                if (val) {
                    this.noScroll()
                } else {
                    this.remScroll()
                }
            },
            money(val) {
                if (val && this.user.is_tax === 1) {
                    this.count_tax(val).then(res => {
                        // console.log('watch money', res)
                        this.taxFee = res.result.taxFee
                    })
                    // .catch((error) => {
                    //     console.log('watch money error', error)
                    // })
                }
            }
        },
        computed: {
            ...mapState(['$image']),
            user() {
                return this.$store.getters.get_user
            },
            stock() {
                let money = this.withdrawMoney
                let count = 0
                if (this.$i18n.locale === 'hk') {
                    count = Math.floor(money / this.stockPrice)
                } else {
                    count = Math.floor((money * (this.exchangeRate || 1)) / this.stockPrice)
                }

                return count
            }
        },
        components: {
            payAccount,
            payPassword
            // noPassword
        }
    }
</script>

<style lang="scss">
    .zhizhao-img {
        width: 180rpx;
        height: 180rpx;
        background-image: url(../../static/add_img.png);
        background-size: 100%;
    }

    page {
        background-color: #f7f7f7;
    }

    .uni-list-cell {
        font-size: 28rpx;
        display: flex;
        align-items: center;
        margin-top: 20rpx;
        // justify-content: center;
    }

    .uni-list-cell-tips {
        font-size: 24rpx;
        color: #999;
        padding-left: 60rpx;
    }

    .content-box {
        width: 100vw;
        overflow-x: hidden;
    }

    .tax_path {
        display: flex;
        margin-top: 20rpx;
        align-items: center;

        .upload-icon {
            margin-left: 40rpx;
            border: 1px #ddd dashed;
            width: 100rpx;
            height: 100rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 40rpx;
        }
    }

    .all-with {
        &.zh {
            color: var(--theme);
        }

        &.hk {
            color: var(--themeHK);
        }
    }

    .option {
        display: flex;
        background-color: #ffffff;

        >view {
            flex: 1;
            text-align: center;
            font-size: 30rpx;
            line-height: 90rpx;
            color: #808080;
        }

        .active {
            position: relative;

            &.zh {
                color: var(--theme);
            }

            &.hk {
                color: var(--themeHK);
            }
        }

        .active::after {
            position: absolute;
            content: '';
            width: 96rpx;
            height: 2rpx;
            bottom: 0;
            left: 50%;
            margin-left: -48rpx;
        }

        .active.zh::after {
            background-color: var(--theme);
        }

        .active.hk::after {
            background-color: var(--themeHK);
        }
    }

    .from {
        padding: 70rpx;
        box-sizing: border-box;
        background-color: #ffffff;
        margin-top: 20rpx;

        .account-input-box {
            border-bottom: 1rpx solid #f0f0f0;
            display: flex;
            align-items: center;
        }

        .account-input {
            line-height: 100rpx;
            height: 100rpx;
            flex: 1;
        }

        .flex {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20rpx;
            color: #bebebe;
        }

        .buttom {
            margin: 0 auto;
            margin-top: 100rpx;
            width: 620rpx;
            height: 90rpx;

            border-radius: 45rpx;
            text-align: center;
            line-height: 90rpx;
            color: #ffffff;

            &.zh {
                background: var(--theme);
            }

            &.hk {
                background: var(--themeHK);
            }
        }

        .flex-tip {
            display: flex;
        }

        .wechat {
            &.zh {
                color: var(--theme);
            }

            &.hk {
                color: var(--themeHK);
            }
        }

        .c7 {
            color: #c7c7c7;
        }
    }

    .rich-box {
        width: 100vw;
        padding: 30rpx;
        overflow: hidden;

        rich-text {
            width: 690rpx;
        }
    }
</style>